<?php

namespace app\model\v1\recovery;

use app\model\system\admin\SystemAdmin;
use app\model\user\User;
use crmeb\traits\ModelTrait;
use think\facade\Db;
use think\Model;


class ConfigActivity extends Model
{

    const SHOW_TYPE_LINE = 1;  //1 显示
    const SHOW_TYPE_UNLINE = 2;  //2 不显示


    use ModelTrait;

    protected $updateTime = false;
    protected $createTime = false;

    protected $hidden = [
    //    'create_time','update_time','delete_time'
    ];

    protected $table = 'eb_config_activity';


    public function admin()
    {
        return $this->hasOne(SystemAdmin::class, 'id', 'create_id');
    }



    /**
     * 添加活动
     * @param $param
     * @return int|string
     */
    public static function addConfigActivity($param = [])
    {
        $add = [
            "create_id"     => $param["admin_id"],  //创建人id
            "title"         => $param["title"] ?? '', //活动标题
            "create_img"         => $param["create_img"] ?? '', //活动封面
            "start_time"    => strtotime($param["start_time"]),  //开始时间
            "end_time"      => strtotime($param["end_time"]),  //结束时间
            "client_type"   => $param["client_type"] ?? '',  //客户端类型
            "type"          => $param["type"] ?? '1',
            "goods_id"          => $param["goods_id"] ?? null,
            "sort"          => $param["type"] ?? 0,
            "integral"      => $param["integral"] ?? '',
            "vip_day"       => $param["vip_day"] ?? '',
            "create_time"   => time(),
        ];
        return self::insert($add);
    }



    /**
     * 获取banner列表
     * @param $param
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     * @throws \think\exception\DbException
     */
    public static function getConfigActivityList($param = [])
    {
        $order = ["id"=>"desc"];
        //按照创建时间排序
        if(!empty($param["order_ctime"])){
            if(!empty($param["order_ctime_sc"])){
                $order = ["id"=>"desc", "create_time"=> $param["order_ctime_sc"]];
            }else{
                //默认按照字段降序排序
                $order = ["id"=>"desc", "create_time"=>"desc"];
            }
        }

        $data["data"] = self::field ("*,FROM_UNIXTIME(start_time) as start_time,FROM_UNIXTIME(end_time) as end_time,FROM_UNIXTIME(create_time) as create_time,
            case when status=1 then '启用' 
                when status=2 then '禁用' 
                end as status_text, 
            case when client_type=1 then 'H5' 
                when client_type=2 then '安卓' 
                when client_type=3 then 'IOS' 
                when client_type=4 then '小程序' 
                end as client_type_text
            ")
            ->with([
                "admin" => function ($query) {
                    $query->field("id,account,real_name");
                }
            ])
            ->where(function ($query) use ($param){
                $query->whereNull("delete_time");
                if(!empty($param['time'])){    //根据创建日期搜索
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                //根据关键字搜索
                if(!empty($param["word"])) $query->where("title",'like', '%'.$param["word"].'%');
                //根据客户端类型搜索
                if(!empty($param["client_type"])) $query->where("client_type", $param["client_type"]);
            })
            ->order($order)
            ->page($param["page"], $param['limit'])
            ->select()->toArray();

        $data["count"] = self::field ("*")
            ->with([
                "admin" => function ($query) {
                    $query->field("id,account,real_name");
                }
            ])
            ->where(function ($query) use ($param){
                $query->whereNull("delete_time");
                if(!empty($param['time'])){    //根据创建日期搜索
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                //根据关键字搜索
                if(!empty($param["word"])) $query->where("title",'like', '%'.$param["word"].'%');
                //根据客户端类型搜索
                if(!empty($param["client_type"])) $query->where("client_type", $param["client_type"]);
            })
            ->count();

        return $data;
    }


    /**
     * 活动管理列表 - 获取客户端类型列表
     * @param $param
     * @return array[]
     */
    public static function getActivityClientTypeList($param = [])
    {
        return [
            [
                "id" => 1,
                "name" => 'H5',
            ],
            [
                "id" => 2,
                "name" => '安卓',
            ],
            [
                "id" => 3,
                "name" => 'IOS',
            ],
            [
                "id" => 4,
                "name" => '小程序',
            ],
        ];
    }



    /**
     * 活动管理列表 - 编辑
     * @param $param
     * @return ConfigBanner
     */
    public static function updateActivity($param = [])
    {
        $update["update_time"] = time();  //更新时间
        if(!empty($param["title"]))         $update["title"] = $param["title"];
        if(!empty($param["start_time"]))    $update["start_time"] = strtotime($param["start_time"]);
        if(!empty($param["end_time"]))      $update["end_time"] = strtotime($param["end_time"]);
        if(!empty($param["client_type"]))   $update["client_type"] = $param["client_type"];
        if(!empty($param["type"]))          $update["type"] = $param["type"];
        if(!empty($param["goods_id"]))          $update["goods_id"] = $param["goods_id"];
        if(!empty($param["sort"]))          $update["sort"] = $param["sort"];
        if(!empty($param["integral"]))      $update["integral"] = $param["integral"];
        if(!empty($param["vip_day"]))       $update["vip_day"] = $param["vip_day"];
        if(!empty($param["create_img"]))       $update["create_img"] = $param["create_img"];
        if(!empty($param["status"]))        $update["status"] = $param["status"]; //1 启用  2禁用

        return self::where("id", $param['id'])->update($update);
    }



    /**
     * banner管理列表 - 启用禁用
     * @param $param
     * @return string
     */
    public static function enableBannerStatus($param = [])
    {
        $status = ConfigActivity::where("id", $param['id'])->value("status");
        $msg = '';
        if($status == 1){   //1启用 2禁用
            $enable = 2;
            $msg = "禁用成功";
        }else{
            $enable = 1;
            $msg = "启用成功";
        }
        ConfigActivity::where("id", $param['id'])->update(['status' => $enable]);
        return $msg;
    }


    public static function getConfigActivity($param = [])
    {
        $data["data"] = self::field ("*,
            case when status=1 then '启用' 
            when status=2 then '禁用' 
            end as status_text 
            ")
            ->with([
                "admin" => function ($query) {
                    $query->field("id,account,real_name");
                }
            ])
            ->where(function ($query) use ($param){
                $query->whereNull("delete_time");
                $query->where("end_time",'>',time());
                $query->where("start_time",'<',time());
                if(!empty($param["client_type"])) $query->where("client_type", $param["client_type"]);
            })
            ->order("sort", "desc")
            ->page($param["page"], $param['limit'])
            ->select()->toArray();

        $data["count"] = self::field ("*,
            case when status=1 then '启用' 
            when status=2 then '禁用' 
            end as status_text 
            ")
            ->with([
                "admin" => function ($query) {
                    $query->field("id,account,real_name");
                }
            ])
            ->where(function ($query) use ($param){
                $query->whereNull("delete_time");
                $query->where("end_time",'>',time());
                $query->where("start_time",'<',time());
                if(!empty($param["client_type"])) $query->where("client_type", $param["client_type"]);
            })
            ->count();
        if(!empty($data["data"])){
            foreach ($data["data"] as $key => &$val){
                if ($val['status'] == 1) {
                    if(empty($param["user_id"])){
                        $val["status"] = 1;
                    }else{
                        $is_rec = self::getUserActivityShow($param["user_id"], $val["type"]);
                        if($is_rec){
                            $val["status"] = 1;
                        }else{
                            $val["status"] = 2;
                        }

                    }
                }
            }
        }

        return $data;
    }


    public static function getUserActivityShow($uid = '', $type='')
    {
        if($type == 1){
            $field = 'is_register_inte';
        }
        if($type == 2){
            $field = 'is_register_member';
        }
        if($type == 3){
            $field = 'is_recommend_goods_id';
        }

         $is_rec = User::where("uid", $uid)->value($field) ?? '';
         if($is_rec==1) return false;

        return true;
    }


    public static function getIntegralNumberValue($client_type = '')
    {
        return self::whereNull("delete_time")
            ->where("status", 1)
            ->where("type", 1)
            ->where("client_type", $client_type)
            ->order("id", "asc")
            ->value("integral") ?? 0;
    }


}